package
{


public class Collection
{
	private var data:Array;
	
	public function Collection(_data:Object=null)
	{
		if(_data==null){
			data=[];
		}else{
			data=getData(_data);
		}
		
	}
	
	//this will sort on ID
	public function sort():void{
		data.sortOn('id',Array.DESCENDING);
	}
	
	//public methods
	
	//retrives
	public function getData(obj:Object):Array{
	
		if(obj is Array){
			return obj.concat();
		}else if(obj is Collection){
			return Collection(obj).toArray();
		}
		
		return [];
	}
	
	public function toArray():Array{
		return data.concat();
	}
	
	public function getLength():uint{
		return data.length;
	}
	
	public function getItemAt(index:uint):Object{
		checkIndex(index,data.length-1);
		return data[index];
	}
	
	//inserts
	public function addItems(items:Object):void{
		addItemsAt(items,data.length);
	}
	
	public function addItemAt(item:Object,index:uint):void{
		checkIndex(index,data.length);
		data.splice(index,0,item);
	}
	
	public function addItem(item:Object):Object{
		data.push(item);
		return item;
	}
	
	public function addItemsAt(items:Object,index:uint):Array{
		checkIndex(index,data.length);
		var arr:Array=getData(items);
		data.splice.apply(data,[index,0].concat(arr));
		return arr;
	}
	
	public function merge(newData:Object):void{
		var arr:Array=getData(newData);
		var l:uint=arr.length;
		var startLength:uint=data.length;
		
		for(var i:uint=0;i<l;i++){
			var item:Object=arr[i];
			if(getItemIndex(item)==-1){
				data.push(item);
			}
		}
	}
	
	public function concat(items:Object):void{
		addItems(items);
	}
	
	//removes
	
	public function removeAll():void{
		data=[];
	}
	
	public function removeItemAt(index:uint):Object{
		var arr:Array=data.splice(index,1);
		return arr[0];
	}
		
	public function removeItem(item:Object):Object{
		var index:int=getItemIndex(item);
		if(item!=-1){
			return removeItemAt(index);
		}
		return null;
	}
	
	//others
	
	public function getItemIndex(item:Object):int{
		return data.indexOf(item);
	}
		
	function checkIndex(index:int,max:int):void{
		if(index>max || index<0){
			//throw new RangeError("Collection : item "+index+" not in range 0 - "+max);
		}
	}
		
	public function replaceItem(newItem:Object,oldItem:Object):Object{
		var index:int=getItemIndex(oldItem);
		if(index!=-1){
			return replaceItemAt(newItem,index);
		}
		return null;
	}
	public function replaceItemAt(newItem:Object,index:uint):Object{
		checkIndex(index,data.length-1);
		var obj:Object=data[index];
		data[index]=newItem;
		return obj;
	}
	
	public function clone():Collection{
		return new Collection(data);
	}
	
	public function contains(item : Object) : Boolean {
		for each(var i:Object in data){
			if(item==i) return true;
		}
		return false;
	}
	
	public function toString():String{
		return "Collection ["+data.join(", ")+"]";
	}
	
	
}

}

